package font

import (
	"context"
	"github.com/gogf/gf/v2/os/glog"
	"golang.org/x/image/font/opentype"
	"golang.org/x/image/font/sfnt"
	"io/ioutil"
)

func NewFont(ctx context.Context, path string) *Font {
	file, err := ioutil.ReadFile(path)
	if err != nil {
		glog.Warningf(ctx, "Font ReadFile error: %+v", err)
	}

	fnt, err := opentype.Parse(file)
	if err != nil {
		glog.Warningf(ctx, "Font Parse error: %+v", err)
	}

	return &Font{
		ctx:  ctx,
		font: fnt,
	}
}

type Font struct {
	ctx  context.Context
	font *opentype.Font
}

func (r Font) Exists(char rune) bool {
	var buf sfnt.Buffer

	idx, err := r.font.GlyphIndex(&buf, char)
	if err != nil {
		glog.Warningf(r.ctx, "Font GlyphIndex error: %+v", err)
	}

	return idx > 0
}
